package cn.hanyx.coder.core.concurrent.juc.cyclicbarrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * CyclicBarrierSample
 *
 * @author hanyx
 * @date 2020/09/24
 */
public class CyclicBarrierSample {
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(5, () -> System.out.println(Thread.currentThread().getName() + " 完成最后任务!"));
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(new CyclicWorker(barrier));
            thread.start();
        }
    }

    static class CyclicWorker implements Runnable {

        private CyclicBarrier barrier;

        public CyclicWorker(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {

            try {
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + " 到达栅栏 A");
                barrier.await();
                System.out.println(Thread.currentThread().getName() + " 冲破栅栏 A");

                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + " 到达栅栏 B");
                barrier.await();
                System.out.println(Thread.currentThread().getName() + " 冲破栅栏 B");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}
